using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;

namespace DownloadManager
{
    public static class ManageDownload
    {
        private static byte[] DownloadData(string url)
        {
            byte[] buffer = new byte[0];

            try
            {
                //Get a data stream from the url                
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                
                req.Timeout = 100000; // 5 seconds in milliseconds
                req.ReadWriteTimeout = 20000; // allow up to 20 seconds to elapse                 
                
                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            
                using (Stream stream = response.GetResponseStream())
                {
                    buffer = ReadFully(stream);
                }
                req.Abort();            
            }
            catch (Exception ex)
            {
                //May not be connected to the internet
                //Or the URL might not exist
                //throw ex;
                return null;
            }
        
            return buffer;
        }

        public static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }

        public static Image GetImageFromURL(string url)
        {
            
            byte[] imageData  = null;
            
            byte[] minData = DownloadData(url);

            if (minData != null)
            {
                imageData = minData;
            }
            else
            {
                return null;
            }
                
            MemoryStream stream = new MemoryStream(imageData);
            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
            stream.Close();

            return img;
        }


    }
}
